import axios from 'axios'

export const request = (options) => {
  // console.log('request-options---', options);
  return new Promise((resolve, reject) => {
    const headerJSON = {
      'Content-Type': 'application/json'
    }
    let parameter = options.data || {}
    let method = options.method || 'get'

    //统一所有请求
    axiosRequest(options.url, parameter, method, headerJSON)
      .then(function (response) {
        let result = response.data

        resolve(result)
      })
      .catch(function (err) {
        let msg = '接口报错了'
        if (
          err.response != undefined &&
          err.response.data != undefined &&
          (err.response.data.msg != undefined || err.response.data.message != undefined)
        ) {
          if (err.response.data.msg != undefined) {
            msg = err.response.data.msg
          } else if (err.response.data.message != undefined) {
            msg = err.response.data.message
          }
        }
        console.log('msg---', msg)
        console.log('err---', err)

        reject(err)
      })
  })
}

export const axiosRequest = (url, params, method, headerJSON) => {
  if (method == 'get') {
    return axiosGet(url, params, headerJSON)
  }
  if (method == 'post') {
    return axiosPost(url, params, headerJSON)
  }
  if (method == 'put') {
    return axiosPut(url, params, headerJSON)
  }
  if (method == 'delete') {
    return axiosDelete(url, params, headerJSON)
  }
}

const Timeout = 60000
export const axiosGet = (url, params, headerJSON) => {
  return axios.get(url, {
    params: params,
    headers: headerJSON,
    timeout: Timeout
  })
}

export const axiosPost = (url, params, headerJSON) => {
  return axios.post(url, params, {
    headers: headerJSON,
    timeout: Timeout
  })
}

export const axiosPut = (url, params, headerJSON) => {
  return axios.put(url, params, {
    headers: headerJSON,
    timeout: Timeout
  })
}

export const axiosDelete = (url, params, headerJSON) => {
  return axios.delete(url, {
    params: params,
    headers: headerJSON,
    timeout: Timeout
  })
}

export default request
